set(TEST_FILE "log.txt")

# add_custom_command does not create a new target. You have to define targets explicitly
# by add_executable, add_library or add_custom_target in order to make them visible to make
add_custom_command(OUTPUT ${TEST_FILE}
    COMMAND touch ${TEST_FILE}

    # Display the given message before the commands are executed at build time
    COMMENT "Creating ${TEST_FILE}"
)

# target zoo is always built
# Please Note that the execution order of ALL targets is weird !!
add_custom_target(zoo ALL
    COMMAND echo "This is ALL target 'zoo', and it depends on ${TEST_FILE}"
    # If the file exists, then commands related to that file won't be executed
    # DONOT let other target depends on the same OUTPUT as current target,
    #   or it may be bad when doing parallel make
    DEPENDS ${TEST_FILE}

    # to make quotes printable,for example
    VERBATIM
)

# target bar is only build when `make bar` is issued
add_custom_target(bar
    # cmake -E support copy/env/echo and so on. use cmake -E to see
    # COMMAND/COMMENT must be upper case
    COMMAND ${CMAKE_COMMAND} -E echo bar:hello
    #COMMAND ${CMAKE_COMMAND} -E environment

    COMMENT "testing add_custom_target 'bar'..."
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}

    #DEPENDS zoo
)
# It seems to be same as `DEPENDS zoo` above
add_dependencies(bar zoo)

# This is the second signature of add_custom_command, which adds a custom command to a target such as a library or executable. This is useful for performing an operation before or after building the target. The command becomes part of the target and will only execute when the target itself is built. If the target is already built, the command will not execute
add_custom_command(TARGET bar
    # On Visual Studio Generators, run before any other rules are executed within the target. On other generators, run just before PRE_LINK commands
    PRE_BUILD
    COMMAND echo -e "\texecuting a PRE_BUILD command"
    COMMENT "This command will be executed before building bar"
    VERBATIM # to support \t for example
)

add_custom_command(TARGET bar
    # Run after sources have been compiled but before linking the binary or running the librarian or archiver tool of a static library. This is not defined for targets created by the add_custom_target() command
    PRE_LINK
    COMMAND echo -e "\texecuting a PRE_LINK command"
    COMMENT "This command will be executed after building bar"
    VERBATIM
)

add_custom_command(TARGET bar
    # Run after all other rules within the target have been executed
    POST_BUILD
    COMMAND echo -e "\texecuting a POST_BUILD command"
    COMMENT "This command will be executed after building bar"
    VERBATIM
)

add_custom_target(clean-cache
    COMMAND rm -f CMakeCache.txt
    COMMENT "Cleaning cache ..."
)

execute_process(COMMAND echo bar OUTPUT_VARIABLE FOO)
message("FOO=" ${FOO})
